package com.aaa.dao.impl;

import com.aaa.dao.ProductDao;
import com.aaa.entity.Product;
import com.aaa.entity.Ptype;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@Repository
public class ProductDaoImpl implements ProductDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    private RowMapper<Product> rowMapper=new RowMapper<Product>() {
        public Product mapRow(ResultSet resultSet, int i) throws SQLException {
            Product product=new Product();
            product.setPid(resultSet.getLong("pid"));
            product.setPname(resultSet.getString("pname"));
            product.setPrice(resultSet.getDouble("price"));
            product.setImgproduct(resultSet.getString("img_product"));
            Ptype ptype = new Ptype();
            ptype.setTid(resultSet.getLong("tid"));
            ptype.setTname(resultSet.getString("tname"));
            product.setPtype(ptype);
            return product;
        }
    };
    public List<Product> listPage(String keyword, Integer offset, Integer limit){
        String sql="select p.pid,p.pname,p.price,p.img_product,t.tid,t.tname from product p left join ptype t on p.tid=t.tid where p.pname like ? order by p.pid desc limit ?,?";
        List<Product> query = this.jdbcTemplate.query(sql, rowMapper, "%" + keyword + "%", offset, limit);
        return query;
    }
    public Integer count(String keyword){
        String sql = "select count(pid) as c from product where pname like ? ";
        Integer result = this.jdbcTemplate.queryForObject(sql, new RowMapper<Integer>() {
            public Integer mapRow(ResultSet resultSet, int i) throws SQLException {
                return resultSet.getInt("c");
            }
        },"%"+keyword+"%");
        return  result;
    }
    public Integer save(Product product){
        String sql="insert into product(pname,price,img_product,tid) values(?,?,?,?)";
        int update = jdbcTemplate.update(sql, product.getPname(), product.getPrice(),product.getImgproduct(),product.getPtype().getTid());
        return update;
    }
    public Integer update(Product product){
        String sql="update product set pname=?,price=?,img_product=?,tid=? where pid=?";
        int update = jdbcTemplate.update(sql,product.getPname(), product.getPrice(),product.getImgproduct(),product.getPtype().getTid(),product.getPid());
        return update;
    }
    public Integer delete(Long pid){
        String sql="delete from product where pid=?";
        int update = jdbcTemplate.update(sql, pid);
        return update;
    }
}

